// 防抖
function debounce(fn, delay) {
  let timer = null;
  function debounceFn(...args) {
    const context = this; 
    if(timer) {
      clearTimeout(timer);
      timer = null;
    }
    timer = setTimeout(() => {
      fn.apply(context, args)
    }, delay)
  }
  return debounceFn;
}

// sleep函数
const sleep = async (delay) => {
  return new Promise((resole) => {
    setTimeout(resole, delay);
  });
};

// 测试
const f = debounce((count) => console.log(count), 2000);
(async function () {
  f(1);
  await sleep(1000);
  f(2); // 1000 < 2000 覆盖重新计时
  await sleep(3000);
  f(3); // 3000 > 2000 上一次可执行，打印2
  await sleep(1500);
  f(4); // 1500 < 2000 覆盖重新计时
  await sleep(2500);
  f(5); // 2500 > 2000 上一次可执行，打印4，本次执行打印5
})();

// useDebounce
const useDebounce = (value, delay) => {
  const [debouncedValue, setDebouncedValue] = useState(value);
  useEffect(() => { 
    const timer = setTimeout(() => {
      setDebouncedValue(value)
    }, delay)
    return () => clearTimeout(timer);
  }, [value, delay])
  return debouncedValue;
}